import 'dart:math';

import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';
import '../../../../data/controllers/exercises_controller.dart';
import '../../exercises_page/models/exercise.dart';
import '../../../gyms/gyms_page/models/gym.dart';

part 'add_exercise_page_state.dart';

class AddExercisePageCubit extends Cubit<AddExercisePageState> {
  TextEditingController nameController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();
  TextEditingController targetGroupController = TextEditingController();
  TextEditingController fromTimeController = TextEditingController();
  TextEditingController toTimeController = TextEditingController();

  final FocusNode nameFocusNode = FocusNode();
  final FocusNode descriptionFocusNode = FocusNode();
  final FocusNode targetGroupFocusNode = FocusNode();
  final FocusNode fromTimeFocusNode = FocusNode();
  final FocusNode toTimeFocusNode = FocusNode();


  bool editMode = false;
  late String exerciseId;
  late String gymId;
  Gym? gym;

  AddExercisePageCubit() : super(AddExercisePageInitial());

  static AddExercisePageCubit get(context) => BlocProvider.of(context);
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();


  void init(Gym? gym , Exercise? exercise) {
    this.gym = gym;
    if(exercise!=null){
      exerciseId = exercise.exerciseId!;
      editMode = true;
      nameController.text = exercise.name ;
      targetGroupController.text = exercise.targetGroup;
      descriptionController.text = exercise.description;
      fromTimeController.text = exercise.fromTime;
      toTimeController.text = exercise.toTime;
      gymId = exercise.gymId;
      emit(AddExercisePageUpdate());
    }else{
      editMode = false;
    }
  }

  clearOldData(){
     nameController.text = "";
     descriptionController.text = "";
     targetGroupController.text = "";
     fromTimeController.text = "";
     toTimeController.text = "";
  }

  addExercise(BuildContext context)async{
    var dialogLoading =  context;
     showDialog(context: context, builder: (context1){
       dialogLoading = context1;
       return const Center(child: CircularProgressIndicator());
     });
    Exercise exercise = Exercise(
      description: descriptionController.text.trim(),
      targetGroup: targetGroupController.text.trim(),
      name: nameController.text.trim(),
      fromTime: fromTimeController.text.trim(),
      toTime: toTimeController.text.trim(),
      gymId: gym!.gymId!,
    );


    emit(AddExercisePageLoading());

    await ExercisesController.addExercise(exercise).then((value){
      clearOldData();
    });
    Navigator.pop(dialogLoading);
    emit(AddExercisePageDone());


  }


  updateExercise(BuildContext context)async{
    var dialogLoading =  context;
    showDialog(context: context, builder: (context1){
      dialogLoading = context1;
      return const Center(child: CircularProgressIndicator());
    });
    print(exerciseId);
    Exercise exercise = Exercise(
      exerciseId: exerciseId,
      description: descriptionController.text.trim(),
      targetGroup: targetGroupController.text.trim(),
      name: nameController.text.trim(),
      fromTime: fromTimeController.text.trim(),
      toTime: toTimeController.text.trim(),
      gymId:gymId,
    );

    emit(AddExercisePageLoading());

    await ExercisesController.updateExercise(exercise).then((value){});
    Navigator.pop(dialogLoading);
    emit(AddExercisePageDone());
  }

  update(){
    emit(AddExercisePageUpdate());
  }

  Future<void> selectDate(BuildContext context ,bool flag) async {
    final TimeOfDay? pickedDate = await showTimePicker(
      initialTime: TimeOfDay.now(),
      context: context,
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: theme.copyWith(
            timePickerTheme: TimePickerThemeData(
              //dialBackgroundColor: theme.colorScheme.surface, // لون الخلفية للساعة والدقائق
              dialTextColor: theme.textTheme.titleLarge?.color, // لون النص للأرقام غير المحددة
              dialHandColor: theme.textTheme.titleLarge?.color?.withOpacity(.2), // لون المؤشر
              //dialTextStyle: theme.textTheme.titleLarge, // لون النص للأرقام المحددة
              //hourMinuteTextColor: theme.textTheme.titleLarge?.color, // لون النص الأساسي (الساعة والدقائق)
              hourMinuteColor: theme.textTheme.titleLarge?.color?.withOpacity(.2), // لون الخلفية للساعة والدقائق
              //hourMinuteTextStyle: theme.textTheme.titleLarge,
            ),
            textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(
                foregroundColor: theme.textTheme.labelLarge?.color, // لون النص للأزرار
              ),
            ),
          ),
          child: child!,
        );
      },
    );

    if (pickedDate != null) {
      const TimeOfDayFormat format = TimeOfDayFormat.HH_colon_mm;

      if(flag) {
        fromTimeController.text = "${pickedDate.hour}:${pickedDate.minute}" ;
      }else{
        toTimeController.text = "${pickedDate.hour}:${pickedDate.minute}" ;
      }
      //datetimeController.text = formattedDate;
    }

    emit(AddExercisePageUpdate());
  }

}
